﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;

namespace StockMentor
{
    public partial class frmReceptii : Form
    {
        private SqlConnection conn;
        public static SqlConnection connStatic;
        private DataSet dsFurnizori, dsProduse, dsProdRecep, dsFirma, dsRecep;
        private SqlDataAdapter daProdRecep, daFirma, daRecep;
        private DataTable dtProdRecep;
        private CurrencyManager crManagerProd, crManagerFurn;
        private int iNrCrt = 0;
        private double dValoareProd = 0, dTotal = 0, dValoareTVA = 0, dValoareAdaos = 0;
        private System.Collections.ArrayList arrList = new System.Collections.ArrayList();
        private int iRecepId = -1;
        private bool bModify = false;
        string sSerieNr = string.Empty;

        private static Form _singletonInstance = null;

        public frmReceptii(SqlConnection conn)
        {
            InitializeComponent();
            this.conn = conn;
		
            txtProdPret.KeyPress += new KeyPressEventHandler(text_KeyPress);
            txtProdPretVz.KeyPress += new KeyPressEventHandler(text_KeyPress);
            txtProdCantRecep.KeyPress += new KeyPressEventHandler(text_KeyPress);
            txtProdCantConform.KeyPress += new KeyPressEventHandler(text_KeyPress);
        }

        void text_KeyPress(object sender, KeyPressEventArgs e)
        {
            switch (((TextBox)sender).Name)
                    {
                        case "txtProdPret":case "txtProdPretVz":case "txtProdCantRecep":case "txtProdCantConform":
                                
                                if (e.KeyChar != (char)Keys.Back)
                                if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
                                    e.Handled = true;
                        break;
                    
                  default:
                        break;
                    }
          //  throw new NotImplementedException();
        }

        private void btnIesire_Click(object sender, EventArgs e)
        {
            this.Close();
            gridProduseNir.Rows.Clear();
        }

        private void frmReceptii_Load(object sender, EventArgs e)
        {
            CustomProcedures.conn = this.conn;

            if (!bModify)
            {
                dsFirma = new DataSet();
                daFirma = new SqlDataAdapter("SELECT TOP 1 firma_cif, firma_recep_serie, firma_recep_ultimnr FROM firma ORDER BY firma_data DESC", conn);
                daFirma.Fill(dsFirma, "firma");

                txtNirSerie.Text = dsFirma.Tables["firma"].Rows[0]["firma_recep_serie"].ToString();
                txtNirNumar.Text = (Convert.ToInt32(dsFirma.Tables["firma"].Rows[0]["firma_recep_ultimnr"]) + 1).ToString();
                this.Text = "Receptii - Adaugare";
            }
            else
            {
                this.Text = "Receptii - Modificare";
                dsRecep = new DataSet();
                daRecep = new SqlDataAdapter("SELECT * FROM receptii WHERE recep_id = " + iRecepId.ToString(), conn); 
                daRecep.Fill(dsRecep, "receptii");

                txtNirSerie.Text = dsRecep.Tables["receptii"].Rows[0]["recep_serie"].ToString();
                txtNirNumar.Text = dsRecep.Tables["receptii"].Rows[0]["recep_numar"].ToString();

                btnNou.Visible = false;
            }

            if (!bModify)
            {
                dsProdRecep = new DataSet();
                daProdRecep = new SqlDataAdapter();

                dtProdRecep = new DataTable("Receptii_Produs");

                DataColumn cIdProd = new DataColumn("recprod_idprod", typeof(int));
                DataColumn cCantRecep = new DataColumn("recprod_cant_recep", typeof(int));
                DataColumn cCantConform = new DataColumn("recprod_cant_conform", typeof(int));
                DataColumn cPretAchiz = new DataColumn("recprod_pret_achizitie", typeof(float));
                DataColumn cPretAmanunt = new DataColumn("recprod_pret_amanunt", typeof(float));
                DataColumn cPretAdaos = new DataColumn("recprod_adaos", typeof(float));
                DataColumn cValTva = new DataColumn("recprod_valoare_tva", typeof(float));
                

                dtProdRecep.Columns.Add(cIdProd);
                dtProdRecep.Columns.Add(cCantRecep);
                dtProdRecep.Columns.Add(cCantConform);
                dtProdRecep.Columns.Add(cPretAchiz);
                dtProdRecep.Columns.Add(cPretAmanunt);
                dtProdRecep.Columns.Add(cPretAdaos);
                dtProdRecep.Columns.Add(cValTva);

                dsProdRecep.Tables.Add(dtProdRecep);
            }

            if (bModify)
            {
                dtProdRecep = CustomProcedures.GETPRODRECEP(iRecepId);//dsReceptii.Tables["receptii"];
            
                /*daProdRecep = new SqlDataAdapter("SELECT recprod_idprod, recprod_cant_recep, recprod_cant_conform, recprod_pret_achizitie FROM receptii_produs WHERE recprod_idrec = " + iRecepId.ToString(), conn);
                daProdRecep.Fill(dsProdRecep, "receptii_produs");*/

                int iNrCrt = 0;
               // double dValoareProd = 0, dTotal = 0;
                foreach (DataRow drProdRecep in dtProdRecep.Rows)
                {
                    arrList.Add(Convert.ToInt32(drProdRecep["recprod_idprod"]));
                    iNrCrt = iNrCrt + 1;
                    //dValoareTVA = Math.Round(Convert.ToDouble(drProdRecep["prod_cota_tva"]) / 100  * Convert.ToDouble(drProdRecep["recprod_pret_achizitie"],2);
                    dValoareProd = Math.Round(Convert.ToDouble(drProdRecep["recprod_pret_amanunt"]) * Convert.ToDouble(drProdRecep["recprod_cant_recep"]),2);
                    gridProduseNir.Rows.Add(Convert.ToInt32(drProdRecep["recprod_idprod"]), iNrCrt.ToString(), Convert.ToString(drProdRecep["prod_denumire"]), Convert.ToString(drProdRecep["prod_um"]), Convert.ToString(drProdRecep["recprod_cant_recep"]), Convert.ToString(drProdRecep["recprod_cant_conform"]), Convert.ToString(drProdRecep["recprod_valoare_tva"]), Convert.ToString(drProdRecep["recprod_pret_achizitie"]), Convert.ToString(drProdRecep["recprod_pret_amanunt"]), Convert.ToString(drProdRecep["recprod_adaos"]), dValoareProd, false);

                    dTotal = dTotal + Math.Round(dValoareProd * Convert.ToInt32(drProdRecep["recprod_cant_recep"]));

                   // comboProdDen.SelectedIndex = -1;

                }

                txtTotal.Text = dTotal.ToString();

            }

            SetControlDataBinding(true);
        }

        private void SetControlDataBinding(bool bFurn)
        {
            
            //crManager = (CurrencyManager)BindingContext[dsReceptii.Tables["receptii"]];


            txtNirData.DataBindings.Clear();
            txtNirNumar.DataBindings.Clear();
            txtNirSerie.DataBindings.Clear();
            txtNirMentiuni.DataBindings.Clear();
            txtNirDelegat.DataBindings.Clear();
            txtNirGestionar.DataBindings.Clear();

            txtAviz.DataBindings.Clear();
            txtAvizData.DataBindings.Clear();

            if (bFurn)
            {
                txtFzBanca.DataBindings.Clear();
                txtFzCif.DataBindings.Clear();
                txtFzEmail.DataBindings.Clear();
                txtFzIBAN.DataBindings.Clear();
                txtFzCod.DataBindings.Clear();
                txtFzAdresa.DataBindings.Clear();
                txtFzRegCom.DataBindings.Clear();
                comboFzDenum.DataBindings.Clear();
            }

            txtProdCantConform.DataBindings.Clear();
            txtProdCantRecep.DataBindings.Clear();
            txtProdPret.DataBindings.Clear();
            txtProdPretVz.DataBindings.Clear();
            //txtAdaos.DataBindings.Clear();
            txtProdTva.DataBindings.Clear();
            txtProdUm.DataBindings.Clear();
            comboProdDen.DataBindings.Clear();

            gridProduseNir.DataBindings.Clear();

            if (bModify)
            {
                //gridProduseNir.DataSource = dsProdRecep.Tables["receptii_produs"];

                txtNirData.DataBindings.Add("Value", dsRecep.Tables["receptii"], "recep_data");
                txtNirNumar.DataBindings.Add("Text", dsRecep.Tables["receptii"], "recep_numar");
                txtNirSerie.DataBindings.Add("Text", dsRecep.Tables["receptii"], "recep_serie");
                txtNirMentiuni.DataBindings.Add("Text", dsRecep.Tables["receptii"], "recep_mentiuni");
                txtNirDelegat.DataBindings.Add("Text", dsRecep.Tables["receptii"], "recep_delegat");
                txtNirGestionar.DataBindings.Add("Text", dsRecep.Tables["receptii"], "recep_gestionar");

                txtAviz.DataBindings.Add("Text", dsRecep.Tables["receptii"], "recep_factura");
                txtAvizData.DataBindings.Add("Text", dsRecep.Tables["receptii"], "recep_data_factura");
            }

            if (bFurn)
            {
                dsFurnizori = new DataSet();
                //SqlDataAdapter daFurnizori = new SqlDataAdapter("SELECT * FROM furnizori ORDER BY furn_denumire ASC", conn);
                SqlDataAdapter daFurnizori = new SqlDataAdapter("SELECT '' AS furn_cif, '' as furn_regc, '' as furn_denumire, '' as furn_adresa, '' as furn_cod, '' as furn_iban, '' as furn_banca, '' as furn_email, '' as furn_data union all select * from furnizori ORDER BY furn_denumire ASC", conn);
                daFurnizori.Fill(dsFurnizori, "furnizori");


                /*txtFzBanca.Text = string.Empty;
                txtFzCif.Text = string.Empty;
                txtFzEmail.Text = string.Empty;
                txtFzIBAN.Text = string.Empty;
                txtFzJudet.Text = string.Empty;
                txtFzLocalit.Text = string.Empty;
                txtFzRegCom.Text = string.Empty;*/


                txtFzBanca.DataBindings.Add("Text", dsFurnizori.Tables["furnizori"], "furn_banca");
                txtFzCif.DataBindings.Add("Text", dsFurnizori.Tables["furnizori"], "furn_cif");
                txtFzEmail.DataBindings.Add("Text", dsFurnizori.Tables["furnizori"], "furn_email");
                txtFzIBAN.DataBindings.Add("Text", dsFurnizori.Tables["furnizori"], "furn_iban");
                txtFzCod.DataBindings.Add("Text", dsFurnizori.Tables["furnizori"], "furn_cod");
                txtFzAdresa.DataBindings.Add("Text", dsFurnizori.Tables["furnizori"], "furn_adresa");
                txtFzRegCom.DataBindings.Add("Text", dsFurnizori.Tables["furnizori"], "furn_regc");
                //comboFzDenum.DataBindings.Add("SelectedValue", dsFurnizori.Tables["furnizori"], "furn_cif");

                // Combobox Databinding
                comboFzDenum.DataSource = dsFurnizori;
                comboFzDenum.DisplayMember = "furnizori.furn_denumire";
                comboFzDenum.ValueMember = "furn_denumire.furn_cif";

                crManagerFurn = (CurrencyManager)BindingContext[dsFurnizori.Tables["furnizori"]];

                if (bModify)
                {
                    dsFurnizori.Tables["furnizori"].PrimaryKey = new DataColumn[] { dsFurnizori.Tables["furnizori"].Columns["furn_cif"] };

                    DataRow drfurn = dsFurnizori.Tables["furnizori"].Rows.Find(dsRecep.Tables["receptii"].Rows[0]["recep_furn_cif"].ToString());
                    comboFzDenum.SelectedIndex = dsFurnizori.Tables["furnizori"].Rows.IndexOf(drfurn);
                }
                else
                    comboFzDenum.SelectedIndex = -1;
                //crManagerFurn.Position = -1;
            }
            dsProduse = new DataSet();
            SqlDataAdapter daFactProd = new SqlDataAdapter("SELECT 0 AS prod_id, '' AS prod_cod, '' as prod_um, '' as prod_denumire, null as prod_cota_tva UNION ALL SELECT * FROM produse ORDER BY prod_denumire ASC", conn);
            daFactProd.Fill(dsProduse, "produse");

            txtProdTva.DataBindings.Add("Text", dsProduse.Tables["produse"], "prod_cota_tva");
            txtProdUm.DataBindings.Add("Text", dsProduse.Tables["produse"], "prod_um");
            
            //Combobox databinding
            comboProdDen.DataSource = dsProduse;
            comboProdDen.DisplayMember = "produse.prod_denumire";
            comboProdDen.ValueMember = "produse.prod_id";

            crManagerProd = (CurrencyManager)BindingContext[dsProduse.Tables["produse"]];

            comboProdDen.SelectedIndex = -1;

           /* txtProdCantConform.DataBindings.Add("Text", dsFirma.Tables["factura_produs"], "factprod_cantconforma");
            txtProdCantRecep.DataBindings.Add("Text", dsFirma.Tables["factura_produs"], "factprod_cant");
            txtProdPret.DataBindings.Add("Text", dsFirma.Tables["factura_produs"], "factprod_pret");*/

        }

        private void comboProdDen_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (crManagerProd != null && crManagerProd.Position <= crManagerProd.Count -1 && comboProdDen.SelectedIndex >= 0)
            crManagerProd.Position = comboProdDen.SelectedIndex ;

            txtProdCantConform.Text = txtProdCantRecep.Text = txtProdPret.Text = txtProdPretVz.Text = string.Empty;
        }

        private void comboFzDenum_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (crManagerFurn != null && crManagerFurn.Position <= crManagerFurn.Count -1 && comboFzDenum.SelectedIndex >= 0)
                crManagerFurn.Position = comboFzDenum.SelectedIndex ;
        }

        private void btnProdAdauga_Click(object sender, EventArgs e)
        {
            iNrCrt ++ ;
            string sMsgText = string.Empty;

            if (comboProdDen.Text.Length == 0)
            {
                MessageBox.Show("Introduceti denumirea articolului!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (txtProdCantRecep.Text.Length == 0)
            {
                MessageBox.Show("Introduceti cantitatea!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (txtProdCantConform.Text.Length == 0)
            {
                MessageBox.Show("Introduceti o valoare valida ca si cantitate conform documente!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (txtProdPret.Text.Length == 0)
            {
                MessageBox.Show("Introduceti pretul de la furnizor!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (txtProdPret.Text.Length == 0)
            {
                MessageBox.Show("Introduceti pretul cu amanuntul!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (arrList != null && arrList.IndexOf(comboProdDen.SelectedValue) >= 0)
            {
                MessageBox.Show("Nu puteti adauga acelasi produs de doua ori!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning );
                comboProdDen.SelectedIndex = -1;
                txtProdCantConform.Text = txtProdCantRecep.Text = txtProdPret.Text = txtProdPretVz.Text = txtProdTva.Text = txtProdUm.Text = string.Empty;
                SetControlDataBinding(false );
                return;
            }
            else
            {
                arrList.Add(comboProdDen.SelectedValue);
                iNrCrt = gridProduseNir.Rows.Count;
                dValoareTVA = Math.Round(Convert.ToDouble(txtProdTva.Text) / 100 * Convert.ToDouble(txtProdPret.Text), 2);
                dValoareProd = Math.Round((Convert.ToDouble(txtProdTva.Text)/100 +1) * Convert.ToDouble(txtProdPret.Text));

                if (dValoareProd > Convert.ToDouble(txtProdPretVz.Text))
                {
                    MessageBox.Show("Valoarea amanuntului este mai mica decat pretul de achizitie + valoarea TVA!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                dValoareAdaos = Math.Round(Convert.ToDouble(txtProdPretVz.Text) - (Convert.ToDouble(txtProdTva.Text)/100 + 1) * Convert.ToDouble(txtProdPret.Text),2);
                gridProduseNir.Rows.Add(comboProdDen.SelectedValue, iNrCrt.ToString(), comboProdDen.Text, txtProdUm.Text, txtProdCantRecep.Text, txtProdCantConform.Text, txtProdTva.Text, txtProdPret.Text, txtProdPretVz.Text, dValoareAdaos, dValoareProd, false);
                
                dTotal = dTotal + Math.Round(dValoareProd * Convert.ToInt32(txtProdCantRecep.Text));
                txtTotal.Text = dTotal.ToString();

                DataRow drProdRecep;
                drProdRecep = dtProdRecep.NewRow();
                drProdRecep["recprod_idprod"] = comboProdDen.SelectedValue;
                drProdRecep["recprod_cant_recep"] = Convert.ToInt32(txtProdCantRecep.Text);
                drProdRecep["recprod_cant_conform"] = Convert.ToInt32(txtProdCantConform.Text);
                drProdRecep["recprod_pret_achizitie"] = Convert.ToDouble(txtProdPret.Text);
                drProdRecep["recprod_pret_amanunt"] = Convert.ToDouble(txtProdPretVz.Text);
                drProdRecep["recprod_adaos"] = dValoareAdaos;
                drProdRecep["recprod_valoare_tva"] = dValoareTVA;
                dtProdRecep.Rows.Add(drProdRecep);

                comboProdDen.SelectedIndex = -1;

                txtProdCantConform.Text = txtProdCantRecep.Text = txtProdPret.Text = txtProdPretVz.Text = txtProdUm.Text = string.Empty;

                SetControlDataBinding(false );

            }
        }

        /*private void gridProduseNir_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView dgv = ((DataGridView)sender);
            if (dgv.CurrentCell.OwningColumn.Name.Equals("colProdSterge") && dgv.Rows.Count > 1)
            {
                dgv.Rows.RemoveAt(dgv.CurrentRow.Index);
                arrList.Remove(dgv.CurrentCell.Value);

                for (int i = dgv.CurrentRow.Index; i < dgv.Rows.Count-1; i++)
                    dgv.Rows[i].Cells["colProdNrCrt"].Value = i;
            }
        }*/

        private void btnProdDel_Click(object sender, EventArgs e)
        {

            for (int i = 0; i < gridProduseNir.Rows.Count - 1; i++)
                if ((bool)gridProduseNir.Rows[i].Cells["colProdSterge"].FormattedValue )
                    {
                        dtProdRecep.Rows.RemoveAt(gridProduseNir.CurrentRow.Index);
                        arrList.Remove(gridProduseNir.Rows[i].Cells["colProdId"].Value);
                        gridProduseNir.Rows.RemoveAt(gridProduseNir.CurrentRow.Index);
                        
                    }
            dTotal = Convert.ToDouble(txtTotal.Text);
            for (int i = 0; i < gridProduseNir.Rows.Count - 1; i++)
            {
                gridProduseNir.Rows[i].Cells["colProdNrCrt"].Value = i + 1;
                dTotal = Math.Round(dTotal - Convert.ToDouble(gridProduseNir.Rows[i].Cells["colPretAmanunt"].Value) * Convert.ToInt32(gridProduseNir.Rows[i].Cells["colProdCantDoc"].Value),2);
            }
            txtTotal.Text = Math.Round(dTotal, 2).ToString();
            SetControlDataBinding(false);
        }

        private void txtProdCantRecep_TextChanged(object sender, EventArgs e)
        {
            if (txtProdCantRecep.Text.Length > 0)
                txtProdCantConform.Text = txtProdCantRecep.Text;
        }

        private void btnSalveaza_Click(object sender, EventArgs e)
        {
            SqlCommand sqlComm;
            int nrcrt;
            try
            {
                string sMsg = string.Empty;

                if (txtAviz.Text.Trim().Length == 0)
                {
                    sMsg = " Factura ";
                    goto msgErr;
                }

                if (comboFzDenum.SelectedIndex == -1 || comboFzDenum.Text.Trim().Length == 0)
                {
                    sMsg = " Furnizor ";
                    goto msgErr;
                }
               /* if (txtNirDelegat.Text.Trim().Length == 0)
                {
                    sMsg = " Delegat ";
                    goto msgErr;
                }
                if (txtNirGestionar.Text.Trim().Length == 0)
                {
                    sMsg = " Gestionar ";
                    goto msgErr;
                }*/



                if (bModify)
                {
                    CustomProcedures.UPDATERECEPTII(iRecepId,
                                                    txtNirSerie.Text,
                                                    Convert.ToInt32(txtNirNumar.Text),
                                                    txtNirData.Value,
                                                    txtFzCif.Text,
                                                    txtAviz.Text,
                                                    txtAvizData.Value,
                                                    txtNirDelegat.Text,
                                                    txtNirGestionar.Text,
                                                    txtNirMentiuni.Text,
                                                    Convert.ToDouble(txtTotal.Text)
                                                    );

                    sqlComm = new SqlCommand("DELETE FROM receptii_produs WHERE recprod_idrec = " + iRecepId.ToString(), conn);
                    sqlComm.ExecuteNonQuery();

                    string strProdRecep = "INSERT INTO receptii_produs(recprod_idrec, recprod_nrcrt, recprod_idprod, " +
                                                                     "recprod_cant_recep, recprod_cant_conform, " +
                                                                     "recprod_pret_achizitie, recprod_pret_amanunt, recprod_adaos, recprod_valoare_tva ) " +
                                                                     "VALUES " +
                                                                     "(@idrec, @nrcrt, @idprod, " +
                                                                     " @cant_recep, @cant_conform, " +
                                                                     " @pret_achizitie, @pret_amanunt, @pret_adaos, @val_tva)";


                    nrcrt = 1;
                    foreach (DataRow dr in dtProdRecep.Rows)
                    {
                        sqlComm = new SqlCommand(strProdRecep, conn);

                        sqlComm.Parameters.Add("@idrec", iRecepId);
                        sqlComm.Parameters.Add("@nrcrt", nrcrt);
                        sqlComm.Parameters.Add("@idprod", Convert.ToInt32(dr[0]));
                        sqlComm.Parameters.Add("@cant_recep", Convert.ToInt32(dr[1]));
                        sqlComm.Parameters.Add("@cant_conform", Convert.ToInt32(dr[2]));
                        sqlComm.Parameters.Add("@pret_achizitie", Convert.ToDouble(dr[3]));
                        sqlComm.Parameters.Add("@pret_amanunt", Convert.ToDouble(dr[4]));
                        sqlComm.Parameters.Add("@pret_adaos", Convert.ToDouble(dr[5]));
                        sqlComm.Parameters.Add("@val_tva", Convert.ToDouble(dr[6]));
                        sqlComm.ExecuteNonQuery();
                        nrcrt++;
                    }

                }
                else
                {
                    if (sSerieNr == txtNirSerie.Text.Trim() + txtNirNumar.Text.Trim()) return;

                    CustomProcedures.INSERTRECEPTII(txtNirSerie.Text,
                                                    Convert.ToInt32(txtNirNumar.Text),
                                                    txtNirData.Value,
                                                    txtFzCif.Text,
                                                    txtAviz.Text,
                                                    txtAvizData.Value,
                                                    txtNirDelegat.Text,
                                                    txtNirGestionar.Text,
                                                    txtNirMentiuni.Text,
                                                    Convert.ToDouble(txtTotal.Text),
                                                    dsFirma.Tables["firma"].Rows[0]["firma_cif"].ToString()
                                                    );

                    sqlComm = new SqlCommand("SELECT @@IDENTITY AS NewId", conn);
                    SqlDataReader reader = sqlComm.ExecuteReader();
                    int idrec = 0;
                    while (reader.Read())
                    {
                        idrec = Convert.ToInt32(reader["NewId"]);
                    }

                    reader.Dispose();
                    reader.Close();

                    string strProdRecep = "INSERT INTO receptii_produs(recprod_idrec, recprod_nrcrt, recprod_idprod, " +
                                                                      "recprod_cant_recep, recprod_cant_conform, " +
                                                                      "recprod_pret_achizitie, recprod_pret_amanunt, recprod_adaos, recprod_valoare_tva ) " +
                                                                      "values " +
                                                                      "(@idrec, @nrcrt, @idprod, " +
                                                                      " @cant_recep, @cant_conform, " +
                                                                      " @pret_achizitie, @pret_amanunt, @pret_adaos, @val_tva)";


                    nrcrt = 1;

                    foreach (DataRow dr in dtProdRecep.Rows)
                    {
                        sqlComm = new SqlCommand(strProdRecep, conn);

                        sqlComm.Parameters.Add("@idrec", idrec);
                        sqlComm.Parameters.Add("@nrcrt", nrcrt);
                        sqlComm.Parameters.Add("@idprod", Convert.ToInt32(dr[0]));
                        sqlComm.Parameters.Add("@cant_recep", Convert.ToInt32(dr[1]));
                        sqlComm.Parameters.Add("@cant_conform", Convert.ToInt32(dr[2]));
                        sqlComm.Parameters.Add("@pret_achizitie", Convert.ToDouble(dr[3]));
                        sqlComm.Parameters.Add("@pret_amanunt", Convert.ToDouble(dr[4]));
                        sqlComm.Parameters.Add("@pret_adaos", Convert.ToDouble(dr[5]));
                        sqlComm.Parameters.Add("@val_tva", Convert.ToDouble(dr[6]));
                        sqlComm.ExecuteNonQuery();

                        try
                        {
                            CustomProcedures.UPDATESTOCURI(Convert.ToInt32(dr[0]), Convert.ToInt32(dr[1]), Convert.ToDouble(dr[4]), 1);
                        }
                        catch
                        {

                        }

                        nrcrt++;
                    }


                    
                    string sUpdFirma = "UPDATE TOP(1) firma SET firma_recep_ultimnr = " + txtNirNumar.Text.Trim();
                    //sUpdFirma = sUpdFirma + " FROM (SELECT TOP (1) * FROM firma ORDER  BY firma_data desc) AS t1 ";
                    sUpdFirma = sUpdFirma + " WHERE firma_data in (SELECT TOP (1) firma_data FROM firma ORDER  BY firma_data desc)";

                    SqlCommand updComm = new SqlCommand(sUpdFirma, conn);

                    
                    SqlDataReader readerFirma = updComm.ExecuteReader();
                    readerFirma.Close();
                    readerFirma = null;
                    iRecepId = idrec;
                }
                sSerieNr = txtNirSerie.Text.Trim() + txtNirNumar.Text.Trim();
                MessageBox.Show("Salvarea s-a efectuat cu succes!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            msgErr: MessageBox.Show("Pentru adaugarea unui Note de Intrare Receptie, campul" + sMsg + "trebuie completat!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Operatiunea s-a efectuat cu errori! Datele nu au fost salvate.", "", MessageBoxButtons.OK , MessageBoxIcon.Error );  
            }
        }

        public static Form GetSingletonInstance(SqlConnection conection)
        {
            if (_singletonInstance == null || _singletonInstance.IsDisposed)
            {
                connStatic = conection;
                _singletonInstance = new frmReceptii(connStatic);
            }
            return _singletonInstance;
        }


        public void SetKeyValues(int iRecepId)
        {
            this.iRecepId = iRecepId;
            bModify = true;
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {

            CustomProcedures.conn = conn;
            SqlDataAdapter daPrintReceptii = CustomProcedures.ReportGETRECEPTII(iRecepId);//dsReceptii.Tables["receptii"];
            dsReceptii dsResult = new dsReceptii();
            daPrintReceptii.Fill(dsResult);
            if (!bModify && dsResult.Tables[1].Rows.Count == 0) MessageBox.Show("Atentie, datele de pe formular nu au fost salvate! Documentul afisat nu contine date.", "", MessageBoxButtons.OK,  MessageBoxIcon.Warning);   

            frmReport formReport = new frmReport("C:\\Users\\Iulia\\Documents\\Visual Studio 2008\\Projects\\StockMentor\\StockMentor\\ReportReceptii.rpt", dsResult);
            formReport.Show();
           
        }

        private void btnNou_Click(object sender, EventArgs e)
        {
            
            iRecepId  = -1;
            gridProduseNir.Rows.Clear();
            dtProdRecep.Rows.Clear();

            dsFirma.Dispose();
            dsFirma = null;
            dsFirma = new DataSet();

            daFirma = new SqlDataAdapter("SELECT TOP 1 firma_cif, firma_recep_serie, firma_recep_ultimnr FROM firma ORDER BY firma_data DESC", conn);
            daFirma.Fill(dsFirma, "firma");

            txtAviz.Text = string.Empty;
            txtAvizData.Value = System.DateTime.Today;
            txtNirDelegat.Text = txtNirGestionar.Text = txtNirMentiuni.Text = string.Empty;
            daFirma.Fill(dsFirma, "firma");

            txtNirSerie.Text = dsFirma.Tables["firma"].Rows[0]["firma_recep_serie"].ToString();
            txtNirNumar.Text = (Convert.ToInt32(dsFirma.Tables["firma"].Rows[0]["firma_recep_ultimnr"]) + 1).ToString();

            sSerieNr = txtNirSerie.Text.Trim() + txtNirNumar.Text.Trim();

            dtProdRecep.Rows.Clear();
            arrList.Clear();
            txtTotal.Text = string.Empty;
            SetControlDataBinding(true);
        }

    }
}
